【发布时间】:2016-04-06 09:32:30
【问题描述】:
我目前正在编写一个日志类(只是为了练习)并遇到了一个问题。我有两个类: Buffer 类充当临时缓冲区,并在其析构函数中刷新自身。还有返回Buffer实例的Proxy类,不用一直写Buffer()。
不管怎样,代码如下:
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
class Buffer
{
private:
std::stringstream buf;
public:
Buffer(){};
template <typename T>
Buffer(const T& v)
{
buf << v;
std::cout << "Constructor called\n";
};
~Buffer()
{
std::cout << "HEADER: " << buf.str() << "\n";
}
Buffer(const Buffer& b)
{
std::cout << "Copy-constructor called\n";
// How to get rid of this?
};
Buffer(Buffer&&) = default;
Buffer& operator=(const Buffer&) & = delete;
Buffer& operator=(Buffer&&) & = delete;
template <typename T>
Buffer& operator<<(const T& v)
{
buf << v;
return *this;
}
};
class Proxy
{
public:
Proxy(){};
~Proxy(){};
Proxy(const Proxy&) = delete;
Proxy(Proxy&&) = delete;
Proxy& operator=(const Proxy&) & = delete;
Proxy& operator=(Proxy&&) & = delete;
template <typename T>
Buffer operator<<(const T& v) const
{
if(v < 0)
return Buffer();
else
return Buffer(v);
}
};
int main () {
Buffer(Buffer() << "Test") << "what";
Buffer() << "This " << "works " << "fine";
const Proxy pr;
pr << "This " << "doesn't " << "use the copy-constructor";
pr << "This is a " << std::setw(10) << " test";
return 0;
}
这是输出:
Copy-constructor called
HEADER: what
HEADER: Test
HEADER: This works fine
Constructor called
HEADER: This doesn't use the copy-constructor
Constructor called
HEADER: This is a test
代码完全符合我的要求,但它取决于 RVO。我多次读到您不应该依赖 RVO,所以我想问一下我该怎么做:
- 完全避免使用 RVO,以便每次都调用复制构造函数
- 避免使用复制构造函数
我已经尝试通过返回引用或移动来避免复制构造函数,但会出现段错误。我猜那是因为 Proxy::operator
我也对功能大致相同的完全不同的方法感兴趣。
【问题讨论】:
-
3.编写不依赖于 RVO 是否发生的代码。
-
我想这是显而易见的选择。但我想避免一个很可能永远不会被调用的复制构造函数。
-
无论如何,您的课程不应该是可复制或可分配的(它有一个
stringstream数据成员。)我真的不知道您要在这里解决什么问题。
标签: c++ copy-constructor rvo