我目前正在写一个日志类(只是为了练习)并遇到了一个问题。我有两个类: 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<< 中的临时变量在返回期间被删除。
我也对大致相同的完全不同的方法感兴趣。