【发布时间】:2015-06-20 20:13:18
【问题描述】:
我声明了一个简单的结构以及默认构造函数、复制构造函数、赋值运算符和析构函数。但是,该结构不能用作 std::map 的值类型。
代码如下:
#include <string.h>
#include <iostream>
#include <string>
#include <map>
class Foo;
std::ostream & operator<<(std::ostream & os, const Foo & v);
typedef unsigned char BYTE;
struct Foo {
char type_; // char to label type
size_t num_; // number of elem, useful if array
size_t total_; // total memory
BYTE * data_; // content of memory
Foo(const char * t) : type_('c'), num_(strlen(t)+1), total_(strlen(t)+1), data_(NULL) {
data_ = new BYTE[total_];
memcpy(data_, t, total_-1);
((char *)data_)[total_-1] = '\0';
}
Foo() : type_(), num_(), total_(), data_(NULL) {}
Foo(const Foo& rhs) : type_(rhs.type_), num_(rhs.num_), total_(rhs.total_), data_(NULL) {
if (total_) {
data_ = new BYTE[total_];
memcpy((char *)data_, (const char *)&rhs.data_, total_);
}
}
Foo & operator=(const Foo& rhs) {
if (&rhs != this) {
releaseData();
type_ = rhs.type_;
num_ = rhs.num_;
total_ = rhs.total_;
data_ = new BYTE[total_];
memcpy(data_, &rhs.data_, total_);
}
return *this;
}
~Foo() {
releaseData();
}
private:
void releaseData() {
delete [] data_; data_ = NULL;
}
};
inline std::ostream & operator<<(std::ostream & os, const Foo & v) {
os << "(type: " << v.type_ << ", num: " << v.num_ << ", total: " << v.total_ << ", data: " << (const char *)v.data_ << ", data addr: " << (void *)v.data_ << ")";
return os;
}
int main() {
Foo c("/home/data/");
std::map<std::string, Foo> store;
store["abc"] = Foo("/home/data/");
std::cout << c << std::endl;
std::cout << store["abc"] << std::endl;
}
代码在使用 gcc 4.9.2 的 Linux 上编译。第一次打印正确打印出字符串,但第二次没有。
这段代码有什么问题?
【问题讨论】:
-
第二个 cout 语句的输出有什么问题?