模板的'strdup()'? [英] A templated 'strdup()'?

查看:157
本文介绍了模板的'strdup()'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

template<typename T>
static T *anydup(const T *src, size_t len) {
    T *ptr = malloc(len * sizeof(T));
    memcpy(ptr, src, (len * sizeof(T)));
    return ptr;
}

这是否正确?当使用int,long等时,我可以预期任何错误吗?我对通用编程很新,我想更多地学习。

Is this proper? Can I expect any errors from this when using an int, long, etc.? I'm very new to generic programming and am trying to learn more.

推荐答案

没有这是不正确的!当你在C ++代码中有一个 malloc()时,你应该变得非常可疑:

No this is not proper ! When you have a malloc() in C++ code, you should become very suspicious:


  • malloc()分配内存,但没有正确创建对象。使用这种内存的唯一方法是使用一个新的。

  • memcpy()不尊重C ++对象的复制语义。这只能用于可复制的类。我会导致很难找到其他地方的bug(浅拷贝,和其他可怕的东西,导致UB)。

  • malloc() allocates memory, but doesn't properly create objects. The only way to work with such memory would be to use a placement new.
  • memcpy() doesn't respect the copy semantic of C++ objects. This could only work with trivially copiable classes. I would cause hard to find bugs elsewhere (shallow copies, and other awful things that lead to UB).

对于像char,int,double这样的基本类型,它会工作。但不适用于更复杂的类型。

For basic types like char, int, double, it would work. But not for more complex types.

替代方案1:调整代码以正确创建和复制对象

Alternative 1: adapt your code to properly create and copy objects

template<typename T>
T *anydup (const T *src, size_t len) {
    T *ptr = new T[len];                        // requires that T has a default constructor
    copy (src, src+len, ptr);                   // requires that T is copyiable
    return ptr;
}

注意:如果用户忘记删除数组,如果用户确实使用 delete [] !为避免这种情况,您可以选择返回 unique_ptr< T []>

Attention: risk of memory leakage if user forget to delete the array, or UB if user doesnet use delete[] ! To avoid this you could opt for returning unique_ptr<T[]>.

替代方法2:删除数组和指针以及内存噩梦:使用向量!

Alternative 2: Get rid of arrays and pointers and memory nightmares: use vectors !

template<typename T>
vector<T> anydup (const vector<T> src) {
    vector<T> v(len);                        // requires that T has a default constructor
    copy (src.cbegin(), src.cend(), v);      // requires that T is copyable
    return v;
}

您可以考虑使用Remy Lebeau建议的复制构造函数创建向量FDinoff在注释中,无论是在函数中还是直接在使用代码中。

You could consider creating the vector using a copy constructor as suggested by Remy Lebeau and FDinoff in the comments, either in the function or directly in the using code.

如果您直接在使用代码中使用 copy(),您很快就会发现, code> copy_if(), copy_backwards()和一些其他不错的< algorithms> 可以根据情况使用。

If you use copy() directly in the using code, you'll soon discover that there are also copy_if(), copy_backwards() and some other nice <algorithms> that could be used depending on circumstances.

这篇关于模板的'strdup()'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆