我有一個CUDA工程一堆類,大多是榮耀struct
s,不構成依賴於對方:封裝vs結構 - 這被認爲是不好的風格?
class A {
public:
typedef boost::shared_ptr<A> Ptr;
A(uint n_elements) { ... // allocate element_indices };
DeviceVector<int>::iterator get_element_indices();
private:
DeviceVector<int> element_indices;
}
class B {
public:
B(uint n_elements) {
... // initialize members
};
A::Ptr get_a();
DevicePointer<int>::iterator get_other_stuff();
private:
A::Ptr a;
DeviceVector<int> other_stuff;
}
DeviceVector
是隻是一個包裝圍繞thrust::device_vector
S和::iterator
可以轉換爲一個原始設備指針。這是必需的,因爲自定義內核被調用並需要處理設備內存。
現在,我不關心封裝,但
- 裸指針的數據已經被暴露,所以使用
A
和B
類可在GPU上 - 運行自定義內核默認構造函數是不希望的話,設備存儲器應當自動分配 - 上
A
>shared_ptr<T>
- 只有極少數方法和
B
需要
所以,我們可以簡單地使用結構
struct A {
void initialize(uint n_elements);
DeviceVector<int> element_indices;
}
struct B {
void initialize(uint n_elements);
A a;
DeviceVector<int> other_stuff;
}
我不知道我是否正確,在封裝的意義上,這實際上相當於讓生活更簡單。如果是這樣,那麼整個概念有什麼不妥之處,並且可能會在某個時候咬人?
C++中類和結構之間的唯一區別是默認可見性(私有類,公共結構)。如果你沒有指定任何參數,編譯器仍然會給你一個默認的構造函數,所以我不確定你的結構例子中初始化函數的用途是什麼。 – jpm 2012-01-27 20:46:13
你的問題確實在問「封裝vs公共數據」。 jpm關於使用'struct'是正確的。 – 2012-01-27 20:56:25
「class」和「struct」在對象設計中有一些更強的內涵,它的價值在於什麼。 C++是混淆這些術語的罪魁禍首。 :) – 2012-01-27 22:23:17